package uk.ac.salfordcc.sccmobile;

import android.app.Activity;
import android.os.Bundle;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sccmobile.helper.AlertDialogManager;
import sccmobile.helper.ConnectionDetector;
import sccmobile.helper.JSONParser;
import android.annotation.TargetApi;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

/**
 * Created by bwarrington on 01/08/13.
 */
public class MyStudentsActivity extends Activity {
    String username, password;
    SharedUtilities sUtils;

    /* sccmobile.helper objects */
    ConnectionDetector cd;
    AlertDialogManager alert;
    JSONParser jsonparser;
    ProgressDialog pDialog;

    ArrayList<HashMap<String, String>> myStudentList;
    ArrayList<HashMap<String, String>> tracksList;

    JSONArray albums = null;
    ListView lv;

    /* Constants */
    private static final String URL = "http://si.salfordcc.ac.uk/ws/srv_myStudents-android.php";
    private static final String TAG_ID = "s_studentReference";
    private static final String STUDENT_NAME = "name";
    private static final String TAG_SONGS_COUNT = "songs_count";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mystudents);

        /* Get username and password data */
        sUtils = new SharedUtilities(getApplicationContext());
        username = sUtils.getStoredPreference("USERNAME");      // Get the stored username
        password = sUtils.getStoredPreference("PASSWORD");      // Get the stored password
        String logStr = "scc MyStudents: Stored User = " + username + " || Stored Password = " + password;
        Log.e(logStr, "");

        /* Create Instances */
        cd = new ConnectionDetector(getApplicationContext());
        alert = new AlertDialogManager();
        jsonparser = new JSONParser();
        myStudentList = new ArrayList<HashMap<String, String>>();

        if(!cd.isConnectingToInternet()){
            alert.showAlertDialog(this, "Internet Connection Error", "Please connect a working internet connection.", false);
            return;
        }
        else{ Log.e("scc Connection: ", "[Enabled]"); }
        new LoadData().execute();

        lv = (ListView)findViewById(R.id.resultView);
        lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3){}
        });
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.sm, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item){
        switch(item.getItemId()){
            case R.id.action_exitapp:
                SharedUtilities.endApplication(this, MyStudentsActivity.this);
                return true;
            case R.id.action_settings:
                Intent intent = new Intent(this, SettingsActivity.class);
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    class LoadData extends AsyncTask<String, String, String>{
        LoadData(){}

        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            pDialog = new ProgressDialog(MyStudentsActivity.this);
            pDialog.setMessage("Getting students, please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(String... args){
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            String json = jsonparser.makeHttpRequest(URL, "GET", params, username, password);

            Log.v("THIS IS THE JSON: ", json);
            if(json != ""){
                try{
                    JSONObject jObj = new JSONObject(json);
                    if(jObj != null){
                        albums = jObj.getJSONArray("students");

                        if(albums != null){
                            for(int i = 0; i < albums.length(); i++){
                                JSONObject c = albums.getJSONObject(i);

                                String s_name = c.getString(STUDENT_NAME);
                                String s_studentReference = c.getString(TAG_ID);

                                double att3wk = c.getDouble("att3wk");
                                int int_att3wk = (int)Math.round(att3wk);

                                HashMap<String, String> map = new HashMap<String, String>();
                                map.put("s_studentReference", s_studentReference);
                                map.put("name", s_name);
                                map.put("att3wk", Integer.toString(int_att3wk));

                                myStudentList.add(map);
                            }
                        }
                    }
                }
                catch(JSONException e){
                    e.printStackTrace();
                }
            }
            return null;
        }

        protected void onPostExecute(String file_url){
            pDialog.dismiss();
            runOnUiThread(new Runnable() {
                public void run() {
                    //String[] values, positions
                    ListAdapter adapter = new SimpleAdapter(
                            MyStudentsActivity.this,
                            myStudentList,
                            R.layout.list_item_students,
                            new String[] { TAG_ID,
                                    STUDENT_NAME, TAG_SONGS_COUNT, "s_studentReference","att3wk" }, new int[] {
                            R.id.album_id, R.id.album_name, R.id.s_studentReference, R.id.s_studentReference , R.id.att3wk});
                    // updating listview
                    //setListAdapter(adapter);
                    lv.setAdapter(adapter);
                }
            });
        }
    }

}